`timescale 1ns/1ps
`default_nettype none
// -----------------------------------------------------------------------------
// 文件名：rtl/forwarding_unit.v
// 作用：数据前递单元
module forwarding_unit(
    input  wire [4:0] ex_rs1,
    input  wire [4:0] ex_rs2,

    input  wire        mem_regwrite,
    input  wire [4:0]  mem_rd,       // EX/MEM 的写回目的寄存器
    input  wire        wb_regwrite,
    input  wire [4:0]  wb_rd,        // MEM/WB 的写回目的寄存器

    output reg  [1:0]  fwd_a_sel,    // 给 ALU A 端
    output reg  [1:0]  fwd_b_sel     // 给 ALU B 端
);
    always @* begin
        // 默认不前递
        fwd_a_sel = 2'b00;
        fwd_b_sel = 2'b00;

        // A 端（rs1）
        if (mem_regwrite && (mem_rd != 5'd0) && (mem_rd == ex_rs1)) begin
            fwd_a_sel = 2'b10; // 来自 EX/MEM
        end else if (wb_regwrite && (wb_rd != 5'd0) && (wb_rd == ex_rs1)) begin
            fwd_a_sel = 2'b01; // 来自 MEM/WB
        end

        // B 端（rs2）
        if (mem_regwrite && (mem_rd != 5'd0) && (mem_rd == ex_rs2)) begin
            fwd_b_sel = 2'b10; // 来自 EX/MEM
        end else if (wb_regwrite && (wb_rd != 5'd0) && (wb_rd == ex_rs2)) begin
            fwd_b_sel = 2'b01; // 来自 MEM/WB
        end
    end
endmodule
